package com.globalwave.pos.inventory.service;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globalwave.common.C;
import com.globalwave.common.cache.CodeHelper;
import com.globalwave.common.exception.BusinessException;
import com.globalwave.pos.inventory.entity.ProductItem;
import com.globalwave.product.entity.Product;

public class ProductItemBO {
	
	private ProductItem productItem ;
	private Log logger = LogFactory.getLog(this.getClass()) ;
	
	public ProductItemBO() {
		
	}
	
	public ProductItemBO(Long itemNumber) {
		get(itemNumber) ;
	}
	
	
	/**
	 * 通过逻辑主键(item number + price percentage)，取得Item Master资料
	 * 
	 * @param itemNumber
	 * @param pricePercentage
	 * @return
	 */
	public ProductItem get(Long itemNumber) {
		
		// get object from cache
		try {
			productItem = (ProductItem)CodeHelper.getObject("Product", itemNumber, ProductItem.class);
		} catch (Exception e) {
			logger.error(e) ;
		}
		
		if (productItem == null) {
			throw new BusinessException("201000", itemNumber);//201000', '未能找到产品，产品编号是[%s]！
		}
		
		return productItem ;
	}

	public void validateSalable(Long itemNumber, Long saleDateNow) throws Exception {
		validateSalable(itemNumber, saleDateNow, null) ;
	}

	public void validateSalable(Long itemNumber, Long saleDateNow, Integer pricePercentage) throws Exception {
		this.productItem = get(itemNumber) ;
		this.productItem.setDateNow(saleDateNow) ;
		
		validateSalable(pricePercentage) ;		
	}
	
	/**
	 * 检查是否可以销售
	 * 
	 * @throws Exception
	 */
	private void validateSalable(Integer pricePercentage) throws Exception {
		if (pricePercentage != null && !productItem.contains(pricePercentage)) {
			throw new BusinessException("err.inv.item.no.percentage");		
		}
		
		if (C.RECORD_ACTIVE.equals(productItem.getStatus_())) {
			throw new BusinessException("err.inv.item.not.active");			
		}
        
		
		if (Product.INVENTORY_LOCK_UNSALABLE.equals(productItem.getSalable_status())) {
			throw new BusinessException("err.inv.item.unsalable");		
		}

	}
	
	public ProductItem get() {
		return productItem;
	}


}
